//
// Created by 夏申频 on 17/1/30.
//

#include "LibCharlsCodec.h"
#include "ImageCodec.h"
#include <libcharls/interface.h>

int jpegLsDecode(ImageCodecContext* c,ImageCodecErr* err){
    JlsParameters jlsParameters;

    JLS_ERROR e = JpegLsReadHeader(c->input, c->inputSize,& jlsParameters);

    if (e != OK) {
        err->code = e;
        return err->code;
    }

    c->meta->width = jlsParameters.width;
    c->meta->height = jlsParameters.height;
    c->meta->channels = jlsParameters.components;
    c->meta->bitsPerSample = jlsParameters.bitspersample;
    c->meta->colorSpace = jlsParameters.colorTransform;

    size_t bufferSize = jlsParameters.bytesperline* jlsParameters.height;

    void* buffer = malloc(bufferSize);

    *(c->output)=(char*)buffer;
    *(c->outputSize) =  bufferSize;
    e = JpegLsDecode(buffer, bufferSize, c->input, c->inputSize,& jlsParameters);

    err->code = e;
    return err->code;

}
int jpegLsEncode(ImageCodecContext* c,ImageCodecErr* err){
    JlsParameters jlsParameters;

    jlsParameters.width = c->meta->width;
    jlsParameters.height = c->meta->height;
    jlsParameters.bitspersample = c->meta->bitsPerSample;
    jlsParameters.components = c->meta->channels;
    int bytesPerSample = (jlsParameters.bitspersample+7)/8;
    jlsParameters.bytesperline =  bytesPerSample*jlsParameters.components* jlsParameters.width;

    void* buffer = malloc(c->inputSize);

    *(c->output)=(char*)buffer;

    JLS_ERROR e = JpegLsEncode(buffer, c->inputSize, (size_t*)c->outputSize,
    c->input, c->inputSize, & jlsParameters);

    err->code = e;

    return err->code;
}